package Servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This servlet is responsible for modifying the attribute isOnline in the Player table in the database.
 * This attribute indicates if a player is online (1) or offline (0).
 * @author Rodge Uy
 */
@PersistenceContext(name = "persistence/LogicalName", unitName = "GooWherePU")
public class PlayerOnlineStatusServlet extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        setOnline(request.getParameter("userName"),request.getParameter("isOnline"));


    }

    private void setOnline(String userName, String isOnlineStr) {

        //convert strings to integers
        int isOnline=Integer.parseInt(isOnlineStr);

        try {

            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            utx.begin();

            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            //this query updates the Online status of the Player
            Query q = em.createNamedQuery("Player.updateOnlineStatus").setParameter("playName", userName).setParameter("isOnline",isOnline);

            int updated = q.executeUpdate();
            System.out.println(updated);

            utx.commit();


        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);

        }
        return;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    protected void persist(Object object) {
        try {
            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            em.persist(object);
            utx.commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }
}
